from django.shortcuts import render
from django.http import JsonResponse
from django.conf import settings
from django.views import View
from QQLoginTool.QQtool import OAuthQQ
from apps.oauth.models import OAuthQQUser
from .utils import loads_id_way, dumps_id_way
from django.contrib.auth import login
import json
import re
from apps.users.models import User
# Create your views here.






# 拿到openid并实现登录
class QQUserView(View):
    def get(self, request):
        '''拿到openid，绑定用户在这里登录未绑定用户返回openid'''
        # 拿到数据
        code = request.GET.get('code')
        # 验证ｃｏｄｅ
        if not code:
            return JsonResponse({'code': 400,
                                'errmsg': '参数缺失',
                                })
        try:
            #　创建ＱＱ对象
            oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                            client_secret=settings.QQ_CLIENT_SECRET,
                            redirect_uri=settings.QQ_REDIRECT_URI,
                            )
            # 拿到token和openid
            token = oauth.get_access_token(code)
            openid = oauth.get_open_id(token)
        except Exception as e:
            return JsonResponse({'code': 400,
                                'errmsg': '获取失败',
                                })




        # 判断是否是已绑定用户
        try:
            qq_user = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # 没绑定
            # 加密openid
            openid_b = dumps_id_way(openid)
            # 返回给前端
            return JsonResponse({'code': 400,
                                 'errmsg': '没绑定',
                                 'access_token': openid_b})

        else:
            # 已绑定
            # 设置session
            login(request, qq_user.user)

            response = JsonResponse({'code': 0,
                                     'errmsg': 'ok'})
            response.set_cookie('username', qq_user.user.username, max_age=3000)

            # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
            from apps.carts.utils import carts_merge
            response = carts_merge(request, response)
            # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

            return response




    def post(self, request):
        '''未绑定用户在这里绑定或者注册绑定'''
        # 拿到数据
        data_dict = json.loads(request.body.decode())
        mobile = data_dict.get('mobile')
        password = data_dict.get('password')
        sms_code_client = data_dict.get('sms_code')
        openid_b = data_dict.get('access_token')
        openid = loads_id_way(openid_b)

        # 效验数据
        if not all([mobile, password, sms_code_client, openid]):
            return JsonResponse({'code': 0,
                                'errmsg': 'ok'})
            # 判断手机号是否合法
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400,
                                'errmsg': '请输入正确的手机号码'})

            # 判断密码是否合格
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return JsonResponse({'code': 400,
                                'errmsg': '请输入8-20位的密码'})

        # 判断是否用户存在
        try:
            user = User.objects.get(modile=mobile)
        except User.DoesNotExist:
            # 不存在就创建
            user = User.objects.create_user(username=mobile,
                                            password=password,
                                            modile=mobile)
        else:
            # 效验密码
            if not user.check_password(password):
                return JsonResponse({'code': 400,
                                    'errmsg': '密码不对'})



        # 绑定用户
        try:
            OAuthQQUser.objects.create(openid=openid,
                                       user=user)
        except OAuthQQUser.DoesNotExist:
            return JsonResponse({'code': 400,
                                'errmsg': '绑定失败'})

        # 设置session

        login(request, user)

        response = JsonResponse({'code': 0,
                                 'errmsg': 'ok'})
        response.set_cookie('username', user.username, max_age=3000)

        return response




# 拿到用户扫码页面
class QQUrlView(View):
    def get(self, request):
        '''拿到扫码登录页'''
        # 拿到数据
        next = request.GET.get('next')
        # 创建ＱＱ对象
        # 获取QQ登录页面网址
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        state=next)

        # 拿到url
        url = oauth.get_qq_url()

        # 返回
        return JsonResponse({'code': 0,
                            'errmsg': 'OK',
                            'login_url': url})






